<?php
/**********************************************************************************
WIKINDX: Bibliographic Management system.
Copyright (C)

This program is free software; you can redistribute it and/or modify it under the terms 
of the GNU General Public License as published by the Free Software Foundation; either 
version 2 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; 
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program; 
if not, write to the 
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

The WIKINDX Team 2007
sirfragalot@users.sourceforge.net
**********************************************************************************/
/*****
*	ADMINCREATOR class.
*
*	Administration of creators
*****/
class ADMINCREATOR
{
// Constructor
	function ADMINCREATOR($db, $vars)
	{
		$this->db = $db;
		$this->vars = $vars;
		include_once("core/session/SESSION.php");
		$this->session = new SESSION();
		include_once("core/template/TEMPLATE.php");
		$this->template = new TEMPLATE('content');
		include_once("core/messages/MESSAGES.php");
		$this->messages = new MESSAGES();
		include_once("core/messages/SUCCESS.php");
		$this->success = new SUCCESS();
		include_once("core/messages/ERRORS.php");
		$this->errors = new ERRORS();
		include_once("core/html/MISC.php");
		include_once("core/html/FORM.php");
		include_once("core/html/TABLE.php");
		include_once("core/creator/CREATOR.php");
		$this->creator = new creator($this->db);
		$this->creators = $this->creator->grabAll();
	}
// check we really are admin
	function gateKeep($method)
	{
		if(!$this->session->getVar("setup_superadmin"))
		{
			include_once("core/authorize/AUTHORIZE.php");
			$authorize = new AUTHORIZE($this->db);
			if($pString = $authorize->initLogon())
				return $pString;
		}
// else, run $method
		return $this->$method();
	}
// display options for categories
	function display($message = FALSE)
	{
		$this->template->setVar("heading", $this->messages->text("heading", "adminCreators"));
		$pString = '';
		if($message)
			$pString .= MISC::p($message);
		if(is_array($this->creators) && !empty($this->creators))
		{
			$pString .= MISC::p($this->messages->text("misc", "creatorMerge"));
			$pString .= FORM::formHeader("mergeCreators");
			$pString .= TABLE::tableStart();
			$pString .= TABLE::trStart();
			$pString .= TABLE::td(FORM::selectFBoxValueMultiple(FALSE, "creatorIds", $this->creators, 20) . 
				MISC::br() . $this->messages->text("hint", "multiples"));
			$pString .= TABLE::tdStart() . MISC::b($this->messages->text("misc", "creatorMergeTarget"));
			$pString .= TABLE::tableStart(FALSE, 0, 0, 0, "left");
			$pString .= TABLE::trStart();// add 0 => IGNORE to creators array
			$temp[0] = $this->messages->text("misc", "ignore");
			foreach($this->creators as $key => $value)
				$temp[$key] = $value;
			$this->creators = $temp;
			unset($temp);
			$pString .= TABLE::td(FORM::selectFBoxValue(FALSE, "creatorIdsOutput", $this->creators, 20));
			$pString .= TABLE::td(FORM::textInput($this->messages->text("resources", "firstname"), 
				"firstname", FALSE, 20, 255));
			$pString .= TABLE::td(FORM::textInput($this->messages->text("resources", "initials"), 
				"initials", FALSE, 6, 255) . MISC::br() . $this->messages->text("hint", "initials"));
			$pString .= TABLE::td(FORM::textInput($this->messages->text("resources", "prefix"), 
				"prefix", FALSE, 11, 10));
			$pString .= TABLE::td(FORM::textInput($this->messages->text("resources", "surname"), 
				"surname", FALSE, 20, 255) . " " . MISC::span('*', 'required'));
			$pString .= TABLE::trEnd();
			$pString .= TABLE::tableEnd();
			$pString .= TABLE::tdEnd();
			$pString .= TABLE::trEnd();
			$pString .= TABLE::tableEnd();
			$pString .= MISC::p(FORM::formSubmit("Proceed"), FALSE, "right");
			$pString .= FORM::formEnd();
		}
		else
			$pString .= MISC::p($this->messages->text("misc", "noCreators"));
		$this->template->setVar('body', $pString);
		return $this->template->process();
	}
// start merging process
	function mergeProcess()
	{
		$this->validateInput();
		$this->creatorIds = $this->vars['creatorIds'];
		$this->newCreatorId = $this->insertCreator();
// NB MySQL bug: http://bugs.mysql.com/bug.php?id=2047 -- append comma temporarily
		foreach($this->creatorIds as $id)
		{
// Remove old creators
			if($id != $this->newCreatorId)
				$this->db->delete("WKX_creator", " WHERE " . $this->db->formatField('id') . '=' . 
				$this->db->tidyInput($id));
			$conditionArray1[] = "FIND_IN_SET(" . $this->db->tidyInput($id) . ", CONCAT(" . 
				$this->db->formatfield('creator1') . ", ','))";
			$conditionArray2[] = "FIND_IN_SET(" . $this->db->tidyInput($id) . ", CONCAT(" . 
				$this->db->formatfield('creator2') . ", ','))";
			$conditionArray3[] = "FIND_IN_SET(" . $this->db->tidyInput($id) . ", CONCAT(" . 
				$this->db->formatfield('creator3') . ", ','))";
			$conditionArray4[] = "FIND_IN_SET(" . $this->db->tidyInput($id) . ", CONCAT(" . 
				$this->db->formatfield('creator4') . ", ','))";
			$conditionArray5[] = "FIND_IN_SET(" . $this->db->tidyInput($id) . ", CONCAT(" . 
				$this->db->formatfield('creator5') . ", ','))";
		}
		$this->db->optimize("WKX_creator");
// remove cache files for creators
		$this->db->deleteCache('resourceCreators');
		$this->db->deleteCache('metadataCreators');
		$condition1 = " WHERE " . implode(" OR ", $conditionArray1);
		$condition2 = " WHERE " . implode(" OR ", $conditionArray2);
		$condition3 = " WHERE " . implode(" OR ", $conditionArray3);
		$condition4 = " WHERE " . implode(" OR ", $conditionArray4);
		$condition5 = " WHERE " . implode(" OR ", $conditionArray5);
		$this->updateTable($condition1, 'creator1');
		$this->updateTable($condition2, 'creator2');
		$this->updateTable($condition3, 'creator3');
		$this->updateTable($condition4, 'creator4');
		$this->updateTable($condition5, 'creator5');
// Refresh the creator list
		$this->creators = $this->creator->grabAll();
		return $this->display($this->success->text("creatorMerge"));
	}
// Remove old creator references from WKX_resource_creator and add new creator reference.  NB -- keep the same order
	function updateTable($condition, $creatorField)
	{
		$resultSet = $this->db->select(array("WKX_resource_creator"), array("id", $creatorField), $condition);
		while($row = $this->db->fetchRow($resultSet))
		{
			$newArray = array();
			$newCreatorIdInserted = FALSE;
			foreach(explode(',', $row[$creatorField]) as $oldId)
			{
				if(array_search($oldId, $this->creatorIds) !== FALSE) // Remove this ID
				{
					if(!$newCreatorIdInserted)
					{
						$newArray[] = $this->newCreatorId;
						$newCreatorIdInserted = TRUE;
					}
				}
				else
					$newArray[] = $oldId;
			}
			$ids = join(',', $newArray);
			$this->db->update('WKX_resource_creator', array($creatorField => $ids), 
				" WHERE " . $this->db->formatField('id') . "=" . $this->db->tidyInput($row['id']));
		}
	}
// Insert new creator or return ID if already exists
	function insertCreator()
	{
		if($this->vars['creatorIdsOutput'])
			return $this->vars['creatorIdsOutput'];
		$firstname = $initials = $prefix = FALSE;
		$fields[] = 'surname';
		$values[] = $surname = trim($this->vars['surname']);
		if(trim($this->vars['firstname']))
		{
			$fields[] = 'firstname';
			$values[] = $firstname = trim($this->vars['firstname']);
		}
		if(trim($this->vars['initials']))
		{
			$initials = $this->creator->formatInitials(trim($this->vars['initials']));
			$fields[] = 'initials';
			$values[] = $initials;
		}
		if(trim($this->vars['prefix']))
		{
			$fields[] = 'prefix';
			$values[] = $prefix = trim($this->vars['prefix']);
		}
		if($id = $this->creator->checkExists($surname, $firstname, $initials, $prefix))
		{
			$this->creatorExists = TRUE;
			return $id;
		}
		$this->creatorExists = FALSE;
// given creator doesn't exist so now write to db
		$this->db->insert('WKX_creator', $fields, $values);
		return $this->db->lastAutoId('WKX_creator');
	}
// bad Input function
	function badInput($error, $method)
	{
		include_once("core/html/CLOSE.php");
		new CLOSE($this->db, $this->$method($error));
	}
// validate input
	function validateInput()
	{
		if(!array_key_exists("creatorIds", $this->vars))
			$this->badInput($this->errors->text("inputError", "missing"), "display");
		if(!array_key_exists("creatorIdsOutput", $this->vars) || !$this->vars['creatorIdsOutput'])
		{
			if(!array_key_exists("surname", $this->vars) || !trim($this->vars['surname']))
				$this->badInput($this->errors->text("inputError", "missing"), "display");
		}
	}
}
?>
